package top.haijunit.navi.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import top.haijunit.framework.core.exception.ExceptionServer;
import top.haijunit.navi.auth.domain.PermissionConvert;
import top.haijunit.navi.auth.domain.PermissionGroupInfo;
import top.haijunit.navi.auth.entity.PermissionGroupEntity;
import top.haijunit.navi.auth.mapper.PermissionGroupMapper;
import top.haijunit.navi.auth.mapper.PermissionMapper;

import java.util.List;


/**
 * 【说明类功能】
 *
 * @author zhanghaijun
 * @since 2024-09-02
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class PermissionGroupService {

    private final PermissionGroupMapper baseMapper;
    private final PermissionMapper permissionMapper;
    private final PermissionConvert converter;

    /**
     * 获取权限组列表
     */
    public List<PermissionGroupInfo> selectList() {
        List<PermissionGroupEntity> entityList = this.baseMapper.selectList(new QueryWrapper<>());
        return converter.convertPermissionGroup(entityList);
    }

    /**
     * 添加权限组
     */
    public Long insert(PermissionGroupInfo info) {
        Assert.notNull(info.getPermissionGroupId(), "权限组编码不能为空");
        if (baseMapper.exists(new LambdaQueryWrapper<PermissionGroupEntity>().eq(PermissionGroupEntity::getPermissionGroupId, info.getPermissionGroupId()))) {
            throw new ExceptionServer("权限组编码已存在，请更换编码！");
        }
        Assert.hasLength(info.getGroupName(), "权限组名称不能为空");
        if (baseMapper.exists(new LambdaQueryWrapper<PermissionGroupEntity>().eq(PermissionGroupEntity::getGroupName, info.getGroupName()))) {
            throw new ExceptionServer("权限组名称已存在，请更换名称！");
        }
        PermissionGroupEntity entity = converter.convert(info);
        this.baseMapper.insert(entity);
        return entity.getPermissionGroupId();
    }

    /**
     * 删除权限组
     */
    public Long delete(Long code) {
        if (permissionMapper.existsPermissionByGroupCode(code)) {
            throw new ExceptionServer("该权限组下存在权限，请先删除权限！");
        }
        LambdaQueryWrapper<PermissionGroupEntity> query = new LambdaQueryWrapper<>();
        query.eq(PermissionGroupEntity::getPermissionGroupId, code);
        this.baseMapper.delete(query);
        return code;
    }
}
